package com.xuecheng.basic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.basic.domain.Category;
import com.xuecheng.basic.mappers.CategoryMapper;
import com.xuecheng.basic.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.commons.model.vo.CategoryVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.BeanHelper;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-17
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public ResponseResult findTreeNodes() {
        //查询1级分类
        LambdaQueryWrapper<Category> qw=new LambdaQueryWrapper<>();
        qw.eq(Category::getParentid,0);
        Category category = this.getOne(qw);
        //转化为vo对象
        CategoryVo root = BeanHelper.copyProperties(category, CategoryVo.class);
        //查询所有的2级分类
        List<CategoryVo> list = findByParentId(root.getId());
        root.setCategoryTreeNodes(list);
        for (CategoryVo vo : list) {
            //根据2级分类，查询次分类下的所有3级分类
            List<CategoryVo> voList = findByParentId(vo.getId());
            vo.setCategoryTreeNodes(voList);
        }
        return ResponseResult.okResult(root);
    }

    public List<CategoryVo> findByParentId(String parentId){
        LambdaQueryWrapper<Category> qw=new LambdaQueryWrapper<>();
        qw.eq(Category::getParentid,parentId);
        List<Category> categories = this.list(qw);
        return BeanHelper.copyWithCollection(categories,CategoryVo.class);
    }
}
